package com.example.shaojun.fragmentpractice;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {

    Button button;
    Button button_1;
    FrameLayout frameLayout;
    AnotherRightFragment anotherRightFragment; //将动态加载的Fragment实例保存起来
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        button_1 = findViewById(R.id.button_1);
        frameLayout = findViewById(R.id.right_frame_layout);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(anotherRightFragment==null){
                    //通过setArguments方法将信息传递给Fragment
                    anotherRightFragment = new AnotherRightFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("name", "Hello");
                    anotherRightFragment.setArguments(bundle);
                }
                replaceFragment(anotherRightFragment);
            }
        });
        replaceFragment(new RightFragment());

        button_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(anotherRightFragment!=null) {
                    //通过Fragment实例直接调用其方法，可用于传递信息
                    anotherRightFragment.print();
                }
            }
        });
    }

    //动态加载(替换)Fragment
    private void replaceFragment(Fragment f){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.right_frame_layout, f);
        transaction.addToBackStack(null); //返回栈效果：将之前的Fragment加入返回栈，按返回键时会返回到之前的Fragment
        transaction.commit();
    }

    public void print(){
        Log.d("MainActivity", "MainActivity print");
    }
}

